(function () {

  // 此文件用于修改主题样式文件时，热更新样式用的。
  
  let host = 'localhost:$[port]'
  let files = new Map()

  let findTargetCss = () => {
    let links = [...document.querySelectorAll('link[rel="stylesheet"]')]
    for (const link of links) {
      let url = new URL(link.href)
      if (url.host === host) {
        files.set(url.pathname, link)
      }
    }
  }

  findTargetCss()

  let ws = new WebSocket(`ws://${host}/`)
  ws.onmessage = (e) => {
    console.log('message', e)
    let data = JSON.parse(e.data)
    if (data.type == 'refresh') {
      if (files.has(data.path)) {
        let node = files.get(data.path)
        let url = new URL(node.href)
        let qs = new URLSearchParams(url.search)
        qs.set('t', new Date().getTime())
        url.search = qs.toString()
        node.href = url.toString()
      }
    }
  }
  ws.onopen = (e) => {
    console.log('open', e)
    ws.send('hello world')
  }
})()